package com.sam.im.heiqun.uis.activities;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.PersistableBundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.utils.overlay.SmoothMoveMarker;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.geocoder.StreetNumber;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.uis.adapters.NearLocationAdpter;
import com.sam.im.heiqun.view.EditTextWithDel;
import com.sam.im.heiqun.view.PullToRefreshListener;
import com.sam.im.heiqun.view.PullToRefreshRecyclerView;
import com.yuyh.library.uis.activitys.BaseActivity;
import com.yuyh.library.utils.DimenUtils;
import com.yuyh.library.utils.DividerItemDecorationUtils;
import com.yuyh.library.utils.ScreenUtil;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;


public class LocationActivity extends BaseActivity implements NearLocationAdpter.NearListClickListener,
        LocationSource, AMapLocationListener, PoiSearch.OnPoiSearchListener, AMap.OnMapLoadedListener,
        AMap.OnCameraChangeListener, GeocodeSearch.OnGeocodeSearchListener, Animation.AnimationListener,
        AMap.CancelableCallback, TextWatcher {

    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.pre_tv_title)
    TextView preTvTitle;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.ok)
    TextView ok;
    @BindView(R.id.nearby)
    PullToRefreshRecyclerView recyclerview;
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.edittext)
    EditTextWithDel edittext;
    @BindView(R.id.gaodemapView)
    MapView gaodemapView;
    @BindView(R.id.loadbar)
    ProgressBar loadbar;
    @BindView(R.id.loadview)
    RelativeLayout loadview;

    private NearLocationAdpter adapter;
    private MapView gaodemap;
    private Button locationBt;
    private AMapLocationClient locationClient;//高德定位类
    private AMapLocationClientOption mLocationOption;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener;
    private AMap aMap;
    private OnLocationChangedListener mListener;
    private UiSettings uiSetting;
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private int currentSize = 10; //每页返回的条数
    private PoiSearch poiSearch;// POI搜索

    private PoiSearch.Query query1;//关键词搜索条件
    private PoiSearch poisearch; //关键词搜索
    private int page = 0;
    private int size = 10;
    private String address;
    private String city;
    private String province;
    private String street;
    private String district;
    private String description;
    private double altitude;
    private String streetNum;
    private String floor;
    private double longitude;
    private double latitude;
    private String poiName;
    private AMapLocation amaplocatoion = null;
    private List<PoiItem> poiItems = new ArrayList<>();
    private int loadmoreTag = 0;
    private boolean istop = false;
    private int firstVisibleItemPosition = -1;
    private String tag;
    private ImageView imgselector;
    private PoiItem selectPoi;
    private Marker marker = null;
    private Animation centerMarker;
    private MarkerOptions markerOption;
    private LatLonPoint point;
    private TextView tvaddr;
    private boolean isselectorItem = false;//是否在选择poi列表
    private boolean isfirstin = true; // 第一次进入页面
    private double oncamerlongitude;
    private double oncamerlatitude;
    private MyLocationStyle myLocationStyle;
    private RegeocodeAddress regeocodeAddress;
    private PopupWindow mypopupwindow;
    private RelativeLayout locationtitle;
    private RelativeLayout relative;

    //定位监听
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("info","ondestroy");
        isfirstin = true ;
        gaodemap.onDestroy();
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_location;
    }
    private void initMaker(double lat, double lut) {
        LatLng latLng = new LatLng(lut, lat);
        marker = aMap.addMarker(new MarkerOptions().position(latLng).title("").snippet("DefaultMarker").visible(true));
        marker.setPositionByPixels(DimenUtils.getScreenWidth() / 2, ScreenUtil.dp2px(150));//设置居中显示不随地图移动
        BitmapDescriptor bitmapDescriptor = marker.getIcons().get(1);
        marker.setIcon(bitmapDescriptor);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void init(Bundle savedInstanceState) {
        preTvTitle.setText(getResources().getString(R.string.location));
        right.setVisibility(View.VISIBLE);
        right.setImageResource(R.drawable.plus_search);
        ok.setVisibility(View.VISIBLE);
        ok.setText(getResources().getString(R.string.send));
//        ok.setBackgroundResource(R.drawable.shape_send_bt);
        ok.setPadding(ScreenUtil.dp2px(5), ScreenUtil.dp2px(5), ScreenUtil.dp2px(5), ScreenUtil.dp2px(5));
        locationtitle = (RelativeLayout) findViewById(R.id.locationtitle);
//        searchrecyclerview = (PullToRefreshRecyclerView) findViewById(R.id.serchrecyclerview);
        relative = (RelativeLayout) findViewById(R.id.relative);
        Intent tagintent = getIntent();
        tag = tagintent.getStringExtra("tag");
        Log.i("info", "tag==" + tag);
        adapter = new NearLocationAdpter(this, poiItems);
        adapter.setItemClickListener(this);
        recyclerview.setPullRefreshEnabled(false);
        recyclerview.setLoadingMoreEnabled(true);
        recyclerview.setPullToRefreshListener(new PullToRefreshListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                currentPage++;
                loadmoreTag++;
                doSearchQuery();
            }
        });
        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recycler, int dx, int dy) {
                super.onScrolled(recycler, dx, dy);//dy>0上  反之 下
                if (!istop && dy > 0) {
                }
                if (istop && firstVisibleItemPosition == 0 && dy < 0) {
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {//不滚动的时候
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerview.getLayoutManager();
                    firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                }
            }
        });
        recyclerview.setAdapter(adapter);
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        recyclerview.addItemDecoration(new DividerItemDecorationUtils(getApplicationContext(), LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.black_divider)));

        gaodemap = (MapView) findViewById(R.id.gaodemapView);
        locationBt = (Button) findViewById(R.id.location_bt);
        //定位按钮
        locationBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startLocation();
            }
        });
        gaodemap.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = gaodemap.getMap();
            Log.i("info","amap=="+aMap);
            if (aMap != null) {
                uiSetting = aMap.getUiSettings();
                aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
            }
        }
        initmaplistener();
        startLocation();
        setLocationStyle();
        edittext.addTextChangedListener(this);
        initpup();
        setLoading(true);
    }
    @BindView(R.id.serchrecyclerview)
    PullToRefreshRecyclerView searchrecyclerview;
    private NearLocationAdpter searchAdapter = null;
    private List<PoiItem> searchPois = new ArrayList<>();

    private void initpup() {
        searchrecyclerview.setPullRefreshEnabled(false);
        searchrecyclerview.setLoadingMoreEnabled(true);
        searchrecyclerview.setPullToRefreshListener(new PullToRefreshListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                page++;
                if (!edittext.getText().toString().equals("")) {
                    searchPoi(edittext.getText().toString(), "");
                } else {
                    searchrecyclerview.setLoadMoreComplete();
                }
            }
        });
        searchAdapter = new NearLocationAdpter(LocationActivity.this, searchPois);
        searchAdapter.setItemClickListener(new NearLocationAdpter.NearListClickListener() {
            @Override
            public void onSelectClick(View view, int position) {
                Log.i("info", "onSelectClick: -----0002----");
                searchAdapter.setShowPosition(position + 1);
                poiItems.clear();//清空
                isselectorItem = true;
                PoiItem poiItem = searchPois.get(position + 1);
                searchPois.clear();
                edittext.setVisibility(View.GONE);
                preTvTitle.setVisibility(View.VISIBLE);
                right.setVisibility(View.VISIBLE);
                relative.setVisibility(View.VISIBLE);
                recyclerview.setVisibility(View.VISIBLE);
                searchrecyclerview.setVisibility(View.GONE);
                ok.setText(getResources().getString(R.string.send));
                tvaddr.setText(poiItem.getAdName() + poiItem.getSnippet() + poiItem.getTitle());
                latitude = poiItem.getLatLonPoint().getLatitude();
                longitude = poiItem.getLatLonPoint().getLongitude();
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15), LocationActivity.this);
//                doSearchQuery();
            }
        });
        searchrecyclerview.setAdapter(searchAdapter);
        searchrecyclerview.setLayoutManager(new LinearLayoutManager(this));
        searchrecyclerview.addItemDecoration(new DividerItemDecorationUtils(getApplicationContext(), LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.black_divider)));

    }
    //设置加载
    private void setLoading(boolean visible){
        if (visible){
            if (edittext.getVisibility() == View.VISIBLE) {
                recyclerview.setVisibility(View.VISIBLE);
                searchrecyclerview.setVisibility(View.GONE);
            }else {
                searchrecyclerview.setVisibility(View.VISIBLE);
                recyclerview.setVisibility(View.GONE);
            }
            recyclerview.setVisibility(View.GONE);
            loadview.setVisibility(View.VISIBLE);
        }else {
            if (edittext.getVisibility() == View.VISIBLE) {
                recyclerview.setVisibility(View.GONE);
                searchrecyclerview.setVisibility(View.VISIBLE);
            }else {
                searchrecyclerview.setVisibility(View.GONE);
                recyclerview.setVisibility(View.VISIBLE);
            }

            loadview.setVisibility(View.GONE);
        }

    }
    //自定义定位小蓝点
    private void setLocationStyle() {
        myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeColor(R.color.red);
        ImageView imgview = new ImageView(this);
        imgview.setImageResource(R.drawable.gaodemaker);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromView(imgview));
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        aMap.setMyLocationStyle(myLocationStyle);
    }

    //添加监听事件
    private void initmaplistener() {
        aMap.setOnCameraChangeListener(this);
        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);
    }

    //开启定位
    private void startLocation() {
        // 设置定位监听
        aMap.setLocationSource(this);
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
        // 设置定位的类型为定位模式，有定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        uiSetting.setScaleControlsEnabled(true);//设置比例尺显示
        uiSetting.setMyLocationButtonEnabled(true);//显示定位按钮
        uiSetting.setZoomControlsEnabled(true);

    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        gaodemap.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        gaodemap.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //locationService.unregisterListener(mListener); // 注销掉监听
        //locationService.stop(); // 停止定位服务
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        gaodemap.onSaveInstanceState(outState);
    }

    @OnClick({R.id.pre_v_back, R.id.right, R.id.ok})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                if (edittext.getVisibility() == View.VISIBLE) {
                    edittext.setVisibility(View.GONE);
                    preTvTitle.setVisibility(View.VISIBLE);
                    right.setVisibility(View.VISIBLE);
                    relative.setVisibility(View.VISIBLE);
                    searchrecyclerview.setVisibility(View.GONE);
                    recyclerview.setVisibility(View.VISIBLE);
                    ok.setText(getResources().getString(R.string.send));
                    searchPois.clear();
                    page = 0;
                    // mypopupwindow.dismiss();
                } else {
                    finish();
                }
                break;
            case R.id.right:
                //Log.i("info","点击搜索");
                if (edittext.getVisibility() == View.GONE) {
                    // mypopupwindow.showAsDropDown(locationtitle);//显示
                    edittext.setVisibility(View.VISIBLE);
                    preTvTitle.setVisibility(View.GONE);
                    right.setVisibility(View.GONE);
                    relative.setVisibility(View.GONE);
                    recyclerview.setVisibility(View.GONE);
                    searchrecyclerview.setVisibility(View.VISIBLE);
                    ok.setText(getResources().getString(R.string.search));
                }

                break;
            case R.id.ok: {
                //发送当前选中位置
                //地图截屏
                Log.i("info", "点击了发送");
                if (edittext.getVisibility() == View.GONE) {
                    cutmapscreen();
                } else {
                    //进行poi检索
                    if (!edittext.getText().toString().equals("")) {
                        searchPois.clear();
                        page = 0;
                        searchPoi(edittext.getText().toString(), city);
                    }
                }
                break;
            }
        }
    }
    //地图截图
    private void cutmapscreen() {
        aMap.getMapScreenShot(new AMap.OnMapScreenShotListener() {
            @Override
            public void onMapScreenShot(Bitmap bitmap) {
                Log.i("info", "地图截屏1");
            }
            @Override
            public void onMapScreenShot(Bitmap bitmap, int status) {
                Log.i("info", "地图截屏2");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                if (null == bitmap) {
                    return;
                }
                String img_name = Environment.getExternalStorageDirectory() + "/test_"
                        + sdf.format(new Date()) + ".png";
                try {
                    FileOutputStream fos = new FileOutputStream(
                            img_name);
                    boolean b = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    try {
                        fos.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    StringBuffer buffer = new StringBuffer();
                    if (b) {
                        buffer.append("截屏成功 ");
                        Intent resultintent = new Intent();
                        if (imgselector.isSelected()) {
                            String thisdis = regeocodeAddress.getDistrict();//区
                            StreetNumber streetNumber = regeocodeAddress.getStreetNumber();//
                            LatLonPoint latLonPoint = streetNumber.getLatLonPoint();
                            String formatAddress2 = regeocodeAddress.getFormatAddress();
                            int index = formatAddress2.indexOf("市");
                            String substring = formatAddress2.substring(index + 1);
                            resultintent.putExtra("city", city);
                            resultintent.putExtra("pro", province);
                            resultintent.putExtra("des", "");
                            resultintent.putExtra("poi", tvaddr.getText().toString());
                            resultintent.putExtra("dis", "");
                            resultintent.putExtra("ste", "");
                            resultintent.putExtra("stenum", "");
                            resultintent.putExtra("lat", latitude);
                            resultintent.putExtra("lut", longitude);
                            resultintent.putExtra("pic", img_name);

                        } else {//列表中选择的
                            resultintent.putExtra("city", selectPoi.getCityName() + "");
                            resultintent.putExtra("pro", selectPoi.getProvinceName() + "");
                            resultintent.putExtra("des", "");
                            resultintent.putExtra("poi", selectPoi.getAdName() + selectPoi.getSnippet() + selectPoi.getTitle());
                            resultintent.putExtra("dis", "");
                            resultintent.putExtra("ste", "");
                            resultintent.putExtra("stenum", "");
                            resultintent.putExtra("lut", selectPoi.getLatLonPoint().getLongitude());
                            resultintent.putExtra("lat", selectPoi.getLatLonPoint().getLatitude());
                            resultintent.putExtra("pic", img_name);
                        }
                        if (null != tag && tag.equals("group")) {
                            setResult(RESULT_OK, resultintent);
                        } else {
                            setResult(11, resultintent);
                        }
                        finish();
                    } else {
                        buffer.append("截屏失败 ");
                    }
                    if (status != 0)
                        buffer.append("地图渲染完成，截屏无网格");
                    else {
                        buffer.append("地图未渲染完成，截屏有网格");
                    }
                    //  Toast.makeText(getApplicationContext(),buffer.toString(),Toast.LENGTH_SHORT).show();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    //item点击事件
    @Override
    public void onSelectClick(View view, int position) {
        Log.i("info", "positon==" + position);
        if (edittext.getVisibility() == View.GONE){
            adapter.setShowPosition(position);
            imgselector.setSelected(false);
            selectPoi = poiItems.get(position);
            double loot = selectPoi.getLatLonPoint().getLongitude();
            double laat = selectPoi.getLatLonPoint().getLatitude();
            LatLng lant = new LatLng(laat, loot);
            //视图移动到选中的定位点
            isselectorItem = true;
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lant, 15), this);
            // aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lant, 15));
        }else {
//            Intent resultintent = new Intent();
//            PoiItem poiItem = searchPois.get(position);
//            resultintent.putExtra("city", poiItem.getCityName() + "");
//            resultintent.putExtra("pro", poiItem.getProvinceName() + "");
//            resultintent.putExtra("des", "");
//            resultintent.putExtra("poi", poiItem.getAdName() + poiItem.getSnippet() + poiItem.getTitle());
//            resultintent.putExtra("dis", "");
//            resultintent.putExtra("ste", "");
//            resultintent.putExtra("stenum", "");
//            resultintent.putExtra("lut", poiItem.getLatLonPoint().getLongitude());
//            resultintent.putExtra("lat", poiItem.getLatLonPoint().getLatitude());
//            resultintent.putExtra("pic", "");
//
//            if (null != tag && tag.equals("group")) {
//                setResult(RESULT_OK, resultintent);
//            } else {
//                setResult(11, resultintent);
//            }
//            finish();
//
            searchAdapter.setShowPosition(position + 1);
            poiItems.clear();//清空
            isselectorItem = true;
            PoiItem poiItem = searchPois.get(position + 1);
            searchPois.clear();
            edittext.setVisibility(View.GONE);
            preTvTitle.setVisibility(View.VISIBLE);
            right.setVisibility(View.VISIBLE);
            relative.setVisibility(View.VISIBLE);
            recyclerview.setVisibility(View.VISIBLE);
            searchrecyclerview.setVisibility(View.GONE);
            ok.setText(getResources().getString(R.string.send));
            tvaddr.setText(poiItem.getAdName() + poiItem.getSnippet() + poiItem.getTitle());
            latitude = poiItem.getLatLonPoint().getLatitude();
            longitude = poiItem.getLatLonPoint().getLongitude();
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15), LocationActivity.this);
//            doSearchQuery();

        }

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (locationClient == null) {
            //初始化定位
            locationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            locationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            locationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            locationClient.startLocation();//启动定位
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (locationClient != null) {
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        locationClient = null;
    }

    // 定位成功
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                /*aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(
                        aMapLocation.getLatitude(), aMapLocation.getLongitude())));
*/
                CameraUpdateFactory.zoomTo(15);
                amaplocatoion = aMapLocation;
                //地址信息
                address = aMapLocation.getAddress();
                //城市
                city = aMapLocation.getCity();
                //省份
                province = aMapLocation.getProvince();
                //街道
                street = aMapLocation.getStreet();
                //区
                district = aMapLocation.getDistrict();
                //位置语意信息
                description = aMapLocation.getDescription();
                altitude = aMapLocation.getAltitude();
                //街道号
                streetNum = aMapLocation.getStreetNum();
                //楼层信息
                floor = aMapLocation.getFloor();
                //经度
                longitude = aMapLocation.getLongitude();
                //纬度
                latitude = aMapLocation.getLatitude();
                //poiname
                poiName = aMapLocation.getPoiName();
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15), this);
                View view = LayoutInflater.from(LocationActivity.this).inflate(R.layout.location_layout_head, null);
                tvaddr = (TextView) view.findViewById(R.id.tv_myaddr);
                imgselector = (ImageView) view.findViewById(R.id.select_address);
                imgselector.setSelected(true);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        adapter.setShowPosition(-1);
                        imgselector.setSelected(true);

                        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15), LocationActivity.this);
                    }
                });
                poiItems.clear();
                tvaddr.setText(district + street + streetNum + poiName);
                recyclerview.addHeaderView(view);
                doSearchQuery();//开始周边检索
                initMaker(longitude, latitude);
                isfirstin = false;
                //marker.setAnimationListener(this);
                //smoothtoLocation(new LatLng(oncamerlatitude,oncamerlongitude),new LatLng(latitude,longitude));
                Log.i("info", "定位成功" + "\n" + "adr==" + address + "\n" + "经度=" + longitude + " 纬度=" + latitude + "\n" + "poiname==" + poiName
                        + "\n" + "city=" + city + "\n" + "省份=" + province + "\n" + "区=" + district + "\n" + "街道=" + street + "\n" + "街道号=" + streetNum + "\n" + "楼层=" + floor + "\n" + "位置语描述=" + description
                );

            } else {
                Log.i("info", "定位失败" + aMapLocation.getErrorCode() + aMapLocation.getErrorInfo());
                // String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                //  Log.e("AmapErr", errText);
            }
        }
    }

    /**
     * 关键词搜索
     */
    public void searchPoi(String msg, String citycode) {

        query1 = new PoiSearch.Query(msg, "地名地址信息|公司企业|公共设施|道路附属设施", citycode); // 第一个参数表示查询关键字，第二参数表示poi搜索类型，第三个参数表示城市区号或者城市名
        query1.setPageNum(page);// 设置查询第几页，第一页从0开始
        query1.setPageSize(size);// 设置每页返回多少条数据
        // 所有poi
        PoiSearch poiSearch2 = new PoiSearch(this, query1);
        //设置搜索范围
        poiSearch2.setOnPoiSearchListener(this);
        poiSearch2.setBound(new PoiSearch.SearchBound(point, 50000, true));
        poiSearch2.searchPOIAsyn();// 异步poi查询
    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery() {

        aMap.setOnMapClickListener(null);// 进行poi搜索时清除掉地图点击事件
        query = new PoiSearch.Query("", "", "");
        //    query = new PoiSearch.Query("", deepType, "北京市");
        // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(currentSize);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        // 所有poi
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        // 设置搜索区域为以lp点为圆心，其周围3000米范围
        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(latitude,
                longitude), 3000));//设置周边搜索的中心点以及半径
        poiSearch.searchPOIAsyn();// 异步搜索

    }

    //搜索结果
    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
          Log.i("info", "i==" + i);
          Log.i("info", "======" + new Gson().toJson(poiResult));
        if (i == 1000) {
            if (poiResult != null) {
                ArrayList<PoiItem> pois = poiResult.getPois();
                if (pois != null && pois.size() > 0) {
                     Log.i("info", "poisize==" + pois.size());
                    if (edittext.getVisibility() == View.VISIBLE) {
                        //searchPois.clear();
                        Log.i("info", "==001==" );
                        searchPois.addAll(pois);
                        searchAdapter.refresh(searchPois);
                        for (int j = 0; j < searchPois.size(); j++) {
                            Log.i("", "onPoiSearched: -------------" + searchPois.get(j).getTitle());

                        }


                        recyclerview.setVisibility(View.GONE);
                        searchrecyclerview.setVisibility(View.VISIBLE);
                    } else {
                        Log.i("info", "==002==" );
                        poiItems.addAll(pois);
                        adapter.notifyDataSetChanged();
                        if (loadmoreTag != 0) {
                            recyclerview.setLoadMoreComplete();
                        }
                    }

                    for (int d = 0; d < pois.size(); d++) {
                        PoiItem poiItem = pois.get(d);
                        String direction = poiItem.getDirection();
                        String adName = poiItem.getAdName();//区
                        String adCode = poiItem.getAdCode();
                        String businessArea = poiItem.getBusinessArea();
                        int distance = poiItem.getDistance();
                        String provinceName1 = poiItem.getProvinceName();//省
                        String cityName = poiItem.getCityName();//市
                        String snippet = poiItem.getSnippet();//
                        String tel = poiItem.getTel();
                        String title = poiItem.getTitle();
                        String s = poiItem.toString();
                        Log.i("info", "周边POI==" + adName + "\n" + "adCode=" + adCode + "\n" + "title=" + title + "\n" + "s==" + s
                                + "\n" + "provice==" + provinceName1 + "\n" + "city==" + cityName + "\n" + "snippet==" + snippet + "\n" + "\n" + "tel==" + tel + "\n"
                                + "businessArea=" + businessArea + "direction" + direction);
                    }
                } else {//无结果



                    if (edittext.getVisibility() == View.VISIBLE) {

                        int itemCount = searchAdapter.getItemCount();
                        if (itemCount>0){
                            showToast(getResources().getString(R.string.get_data_all));
                        }else {
                            showToast(getResources().getString(R.string.not_have_result));
                        }

                        searchrecyclerview.setLoadMoreComplete();
                        searchAdapter.notifyDataSetChanged();
                    }else {

                        int itemCount = adapter.getItemCount();
                        if (itemCount>0){
                            showToast(getResources().getString(R.string.get_data_all));
                        }else {
                            showToast(getResources().getString(R.string.not_have_result));
                        }

                        recyclerview.setLoadMoreComplete();//没有更多结果了
                        adapter.notifyDataSetChanged();
                        searchPois.clear();
                    }
                    page = 0;
                }
            } else {//搜索结果为空
                // Log.i("info", "结果为空");
            }
        }
        setLoading(false);
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onMapLoaded() {
        CameraUpdateFactory.zoomTo(15);
        locationBt.setVisibility(View.VISIBLE);
        locationBt.setEnabled(true);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        double longitude = cameraPosition.target.longitude;
        double latitude = cameraPosition.target.latitude;
        // Log.i("info", "==onCameraChange==" + cameraPosition);
        locationClient.stopLocation();
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        oncamerlongitude = cameraPosition.target.longitude;
        oncamerlatitude = cameraPosition.target.latitude;
        point = new LatLonPoint(oncamerlatitude, oncamerlongitude);
        // Log.i("info","first=="+isfirstin+"  item="+isselectorItem);
        if (!isselectorItem) {
            //Log.i("info","开始搜索");
            getAddress(point);
        }
        isfirstin = false;
        isselectorItem = false;
        //Log.i("info", "==onCameraChangeFinish==" + cameraPosition);
    }

    private GeocodeSearch geocoderSearch;
    /**
     * 响应逆地理编码
     */
    public void getAddress(final LatLonPoint latLonPoint) {
// showDialog();
        setLoading(true);
        // Log.i("info", "lat==" + latLonPoint.getLongitude() + "lut=" + latLonPoint.getLatitude());
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500,
                GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        geocoderSearch.getFromLocationAsyn(query);//设置同步逆地理编码请求
    }

    /**
     * 地理编码查询回调
     *
     * @param result
     * @param i
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int i) {

        if (result != null) {
            Log.i("info","地理编码查询有结果");
            regeocodeAddress = result.getRegeocodeAddress();
            StreetNumber streetNumber = regeocodeAddress.getStreetNumber();
            String formatAddress = regeocodeAddress.getFormatAddress();
            Log.i("info", "street==" + streetNumber + "addr==" + formatAddress);
            List<PoiItem> searchedpois = regeocodeAddress.getPois();
            int index = formatAddress.indexOf("市");
            LatLonPoint latLonPoint = regeocodeAddress.getStreetNumber().getLatLonPoint();
            tvaddr.setText(formatAddress.substring(index + 1));
            imgselector.setSelected(true);
            adapter.setShowPosition(-1);
            poiItems.clear();
            poiItems.addAll(searchedpois);
            adapter.notifyDataSetChanged();
            if (latLonPoint != null) {
                latitude = latLonPoint.getLatitude();
                longitude = latLonPoint.getLongitude();
            }
        }else {
            Log.i("info","地理编码没有结果");
        }
        setLoading(false);
    }
    /**
     * 逆地理编码回调
     *
     * @param geocodeResult
     * @param i
     */
    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
        Log.i("info", "逆地理编码回调 i==" + i);
        List<GeocodeAddress> geocodeAddressList = geocodeResult.getGeocodeAddressList();
        for (int f = 0; f < geocodeAddressList.size(); f++) {
            String formatAddress = geocodeAddressList.get(f).getFormatAddress();
            Log.i("info", "addr==" + formatAddress);

        }
    }

    @Override
    public void onAnimationStart() {

    }

    @Override
    public void onAnimationEnd() {

    }

    /**
     * 定位后平滑移动
     */
    private void smoothtoLocation(LatLng l1, LatLng l2) {

        // 获取轨迹坐标点
        LatLngBounds bounds = new LatLngBounds(l1, l2);
        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
        SmoothMoveMarker smoothMarker = new SmoothMoveMarker(aMap);
        // 设置滑动的图标
        smoothMarker.setDescriptor(BitmapDescriptorFactory.fromResource(R.drawable.gaodemapmark));
       /* LatLng drivePoint = l1;
        Pair<Integer, LatLng> pair = SpatialRelationUtil.calShortestDistancePoint(points, drivePoint);
        points.set(pair.first, drivePoint);
        List<LatLng> subList = points.subList(pair.first, points.size());*/
        // 设置滑动的轨迹左边点
        //  smoothMarker.setPoints(subList);
        // 设置滑动的总时间
        smoothMarker.setTotalDuration(200);
        // 开始滑动
        smoothMarker.startSmoothMove();
    }

    @Override
    public void onFinish() {

    }

    @Override
    public void onCancel() {

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {//输入完毕开始搜索
//        if (!"".equals(edittext.getText().toString())) {
//            searchPois.clear();
//            page = 0;
//            searchPoi(edittext.getText().toString().trim(), "");
//        }
    }
}
